package com.self.cloumall.seckill.controller;

import com.self.cloudmall.common.dto.SeckillSkuDto;
import com.self.cloudmall.common.utils.R;
import com.self.cloumall.seckill.service.SeckillSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class SeckillController {

    @Autowired
    private SeckillSkuService seckillSkuService;

    /**
     * 获取当前正在秒杀的商品
     * @return
     */
    @GetMapping("/curSeckillSkus")
    @ResponseBody
    public R getCurSeckillSkus(){
        List<SeckillSkuDto> skus = seckillSkuService.getCurSeckillSkus();
        return R.ok().setData(skus);
    }

    @GetMapping("/seckill/{skuId}")
    @ResponseBody
    public R getSeckillSkuBySkuId(@PathVariable("skuId") Long skuId){
        SeckillSkuDto skuDto= seckillSkuService.getSeckillSkuBySkuId(skuId);
        return R.ok().setData(skuDto);
    }

    @GetMapping("/kill")
    public String  seckillSku(String killId, Integer num, String key, Model model){
        if (StringUtils.isEmpty(key)){
            model.addAttribute("msg","秒杀随机码不能为空");
        }else if (num == null || num <= 0 ){
            model.addAttribute("msg","秒杀数量不能小于等于0");
        }else if (StringUtils.isEmpty(killId) || !killId.contains("_")){
            model.addAttribute("msg","商品ID不能篡改");
        }
        R r = seckillSkuService.seckillSku(killId, num, key);
        if (!r.isSuccess()){
            model.addAttribute("msg",r.get("msg"));
        }else{
            model.addAttribute("msg","0");
            model.addAttribute("orderSn",r.getData());
        }
        return "success";
    }
}
